﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace Windows.Security.Authentication.Web
{
    public partial class WebAuthenticationBrokerUI : UserControl
    {
        public Uri StartUri {get;set;}
        public Uri EndUri {get;set;}
        public WebAuthenticationResult Result {get;set;}
        public bool IsComplete {get;set;}
        WebAuthenticationOptions WebAuthOptions;

        public WebAuthenticationBrokerUI()
        {
            InitializeComponent();
            IsComplete = false;
            browser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
            browser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);

        }

        ~WebAuthenticationBrokerUI()
        {
            browser.Navigated -= new EventHandler<System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
            browser.LoadCompleted -= new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);
        }
        public void Launch(Uri startUri, Uri endUri = null, WebAuthenticationOptions webAuthenticationOptions=WebAuthenticationOptions.None)
        {
            var rootFrame = (PhoneApplicationFrame)Application.Current.RootVisual;
            var rootPage = (PhoneApplicationPage)rootFrame.Content;
            rootPage.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(rootPage_BackKeyPress);

            wasCanceled = false;
            StartUri = startUri;
            EndUri = endUri;
            this.WebAuthOptions = webAuthenticationOptions;
            browser.Navigate(StartUri);
        }

        void rootPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            backToApp();
            e.Cancel = true;
        }

        private void backToAppButton_Click(object sender, RoutedEventArgs e)
        {
            backToApp();
        }

        private void backToApp()
        {
            Result = new WebAuthenticationResult
            {
                ResponseStatus = WebAuthenticationStatus.UserCancel,
                ResponseData = "",
                ResponseErrorDetail = 0
            };
            var rootFrame = (PhoneApplicationFrame)Application.Current.RootVisual;
            var rootPage = (PhoneApplicationPage)rootFrame.Content;
            rootPage.BackKeyPress -= new EventHandler<System.ComponentModel.CancelEventArgs>(rootPage_BackKeyPress);

            IsComplete = true;
        }



        private void startOverButton_Click(object sender, RoutedEventArgs e)
        {
            browser.Navigate(StartUri);
            wasCanceled = false;
        }
        private void browser_Navigating(object sender, Microsoft.Phone.Controls.NavigatingEventArgs e)
        {
            if (this.WebAuthOptions == WebAuthenticationOptions.None && e.Uri.OriginalString.StartsWith(EndUri.OriginalString, StringComparison.InvariantCultureIgnoreCase))
            {
                var resultData = e.Uri;
                Result = new WebAuthenticationResult
                {
                    ResponseStatus = WebAuthenticationStatus.Success,
                    ResponseData = resultData,
                    ResponseErrorDetail = 0
                };
                IsComplete = true;
                wasCanceled = true;
                e.Cancel = true;
            }
            
        }

        private void browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            // additional stuff will happen here.. but skipping for now
            var test = e;
        }
        void browser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!String.IsNullOrEmpty(WebAuthenticationBrokerSettings.PageTweaks) )
            {
                browser.InvokeScript(WebAuthenticationBrokerSettings.PageTweaks);
            }
        }


        bool wasCanceled = false;
        private void browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
        {
            e.Handled = true;

            if (wasCanceled)
                return;
            Result = new WebAuthenticationResult
            {
                ResponseStatus = WebAuthenticationStatus.ErrorHttp,
                ResponseData = "",
                ResponseErrorDetail = 404
            };
            IsComplete = true;
        }
    }
}
